<template>
	<view class="content"
		style="position: fixed;top: 0;left: 0;z-index: 777;width: 100%;height: 100vh;background-color: #000;">
		<camera :binderror="handleCameraError" :device-position="devicePosition" :flash="isOpenFlash"
			style="width: 100%; height: 85vh;position: relative;">
			<cover-view class="btns_top" style="width: 100%;height: 100rpx;">
				<cover-image class="item" @tap="setDelay" :src="`../../static/${currentValue ? '3' : 'yanshi'}.png`"></cover-image>
				<cover-image class="item" @tap="changeFlash" :src="`../../static/${isOpenFlash === 'off' ? 'flashon' : 'flash_auto2'}.png`"></cover-image>
			</cover-view>
			<cover-view class="delay" v-if="isOpenDelay">
				<cover-view class="children_view" @click="setDelayTime(0)">关闭</cover-view>
				<cover-view class="children_view" @click="setDelayTime(3)" :class="{isSelect: currentValue == 3}">3秒</cover-view>
				<cover-view class="children_view" @click="setDelayTime(5)" :class="{isSelect: currentValue == 5}">5秒</cover-view>
				<cover-view class="children_view" @click="setDelayTime(10)" :class="{isSelect: currentValue == 10}">10秒</cover-view>
			</cover-view>
			<cover-view class="countdown-timer" v-if="countdown > 0">
				<cover-view style="padding: 15px">{{ countdown }}</cover-view>
			</cover-view>
		</camera>
		<view class="btns" style="width: 100%;height: 15vh;background: #3B4144;">
			<view class="btn_center">

				<view class="shot">
					<view class="item_cneter" @tap="startCountdown" :class="{isStartDistinguish: isStartDistinguish}">
						<view class="radius"></view>
					</view>
				</view>
				<image class="item xiangce" @tap="chooseImage" src="../../static/xiangce.png"></image>
				<image class="item" @tap="reverseCamera" src="../../static/camear.png"></image>
			</view>
		</view>
	</view>
</template>

<script>
import { recordAdd, animal_list } from "@/api/login";
export default {
	data() {
		return {
			authCamera: false,
			showHeader: true,
			ctxHeader: null,
			devicePosition: 'back',
			isOpenFlash: 'off',
			imgURl:'',
			alert: false,
			countdown:0,
			intervalId:null,
			isOpenDelay: false,
			currentValue: 0,
			isStartDistinguish: false,
			animal_list:[],
		}
	},
	onLoad() {
		this.getAnimal_list();
		this.checkCameraAuth();
		this.getLocation();
	},
	methods: {
		async getAnimal_list(){
			const res = await animal_list()
			console.log(888888888, res);
			this.animal_list = res.data.map(item => item.name)
			
		},
		setDelayTime(val){
			this.currentValue = val;
			this.isOpenDelay = false;
		},
		setDelay(){
			this.isOpenDelay = true;
		},
		changeFlash() {
			this.isOpenFlash = this.isOpenFlash === 'on' ? 'off' : 'on';
		},
		chooseImage() {
			let that = this;
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: (res) => {
					that.imgURl = res.tempFilePaths[0];
					uni.getFileSystemManager().readFile({
						filePath: res.tempFilePaths[0], // 读取图片文件
						encoding: 'base64', // 编码格式为base64
						success: function (fileRes) {
							console.log(fileRes); // 输出Base64格式的图片数据
							that.newPath = fileRes.data
							that.uploadImage()
						},
						fail: function (error) {
							console.error('读取文件失败：', error);
						}
					});
				}
			});
		},
		uploadImage() {
			uni.showLoading({
				title: '请勿操作识别中...',
				mask: true
			});
			if(!uni.getStorageSync("access_token")){
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}
			const params = {
				image: this.newPath,
				baike_num: '10',
				top_num: '10',
				'access_token': uni.getStorageSync("access_token")
			};

			const header = {
				'Content-Type': 'application/x-www-form-urlencoded',
			};
			let that = this
			uni.request({
				url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal',
				method: 'POST',
				data: params,
				header: header,
				success: (res) => {
					uni.hideLoading();
					console.log(222, res);
					if (res.data.result[0].name === '非动物') {
						uni.showToast({
							title: '未识别到动物',
							icon: 'none'
						})
					} else {
						that.toStorage(res.data.result)
					}
					that.isStartDistinguish = false;
				},
				fail: () => {
					this.result = '请求失败';
					that.isStartDistinguish = false;
				}
			});
		},
		toStorage(result) {
			console.log('toStorage', result)
			let that = this
			this.result = result;
			let list = [
				{
					alert: that.animal_list.includes(result[0].name),
					imgurl: this.imgURl,
					result: result,
					isChecked: false,
					createTime: that.getDate()
				}
			]
			uni.setStorageSync('curhistoryList', list)
			that.upLoadFile();
			uni.navigateTo({
				url: '/pages/detail/index'
			})
		},
		getDate() {
			var now = new Date();
			var year = now.getFullYear();
			var month = now.getMonth() + 1; // 月份是从0开始的，所以需要+1
			var day = now.getDate();
			var hours = now.getHours();
			var minutes = now.getMinutes();
			var seconds = now.getSeconds();

			// 补零操作，确保月、日、时、分、秒都是两位数
			month = (month < 10 ? "0" : "") + month;
			day = (day < 10 ? "0" : "") + day;
			hours = (hours < 10 ? "0" : "") + hours;
			minutes = (minutes < 10 ? "0" : "") + minutes;
			seconds = (seconds < 10 ? "0" : "") + seconds;
			console.log('getDate', year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds)
			return year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
		},
		startCountdown() {
			clearInterval(this.intervalId);
			this.isStartDistinguish = true;
			this.countdown = this.currentValue; // 设置倒计时时间为3秒
			this.intervalId = setInterval(() => {
				this.countdown -= 1;
				if (this.countdown <= 0) {
					clearInterval(this.intervalId); // 倒计时结束，清除定时器
					this.takePhotoByHead(); // 调用拍照函数
				}
			}, 1000);
		},
		upLoadFile(){
			let result
			if (uni.getStorageSync("curhistoryList")) {
				let list = uni.getStorageSync("curhistoryList");
				let index = list.length - 1;
				result = list[index].result;
				result.forEach((item, ii) => {
					if (ii === 0) {
						item.show = true;
					} else {
						item.show = false;
					}
				});
				const params = {
					...result[0],
					pic: this.newPath,
					isWarningAnimals: this.animal_list.includes(this.result[0].name)
				}
				recordAdd([params])
			}
			
		},
		//拍摄头像
		takePhotoByHead() {
			let that = this;
			this.showHeader = true //开启拍照
			this.ctxHeader = uni.createCameraContext();
			this.ctxHeader.takePhoto({
				quality: 'high',
				success: (res) => {
					console.log(res)
					uni.compressImage({
						src: res.tempImagePath,
						quality: 90, //压缩比例
						success: ress => {
							this.imgURl = ress.tempFilePath; //图片
							uni.getFileSystemManager().readFile({
								filePath: ress.tempFilePath, // 读取图片文件
								encoding: 'base64', // 编码格式为base64
								success: function (fileRes) {
									console.log(fileRes); // 输出Base64格式的图片数据
									that.newPath = fileRes.data
									that.uploadImage()
								},
								fail: function (error) {
									console.error('读取文件失败：', error);
								}
							});
						}
					})


				}
			});
		},
		handleCameraError() {
			uni.showToast({
				title: '用户拒绝使用摄像头',
				icon: 'none'
			})
		},
		reverseCamera() {
			this.devicePosition = (("back" === this.devicePosition) ? "front" : "back")
		},
		checkCameraAuth() {
		  const that = this;
		  uni.getSetting({
			success(res) {
			  if (!res.authSetting['scope.camera']) {
				// 摄像头权限未开启
				uni.showModal({
				  title: '提示',
				  content: '需要您授权摄像头权限',
				  success: function (res) {
					if (res.confirm) {
					  // 引导用户到设置页面开启权限
					  uni.openSetting({
						success: function (dataAu) {
						  if (dataAu.authSetting['scope.camera']) {
							// 用户打开了权限
							uni.showToast({
							  title: '摄像头权限已开启',
							  icon: 'none'
							});
						  } else {
							// 用户未开启权限
							uni.showToast({
							  title: '摄像头权限未开启',
							  icon: 'none'
							});
						  }
						}
					  });
					}
				  }
				});
			  }
			}
		  });
		},
	}
}
</script>

<style lang="scss" scoped>
.content {
	display: flex;
	flex-direction: column;
	// align-items: center;
	justify-content: center;
	background: #fff;
	box-sizing: border-box;
	height: 100%;
	width: 100vw;

	.btns_top {
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-top: 60px;
		position: relative;

		.item {
			width: 30px;
			height: 30px;
		}
	}
	.delay{
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-left: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		width: 200px;
		.children_view{
			color: #fff;
			padding: 10px;
			font-size: 14px;
		}
	}
	.isSelect{
		color: yellow !important;
	}

	.btns {
		display: flex;
		justify-content: space-around;
		align-items: center;

		.btn_center {
			border-radius: 40px;
			background-color: cadetblue;
			width: 180px;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10px 10px;
		}

		.item_cneter {
			width: 60px;
			height: 80px;
			background-color: cadetblue;
			border-radius: 26px;
			display: flex;
			align-items: center;
			justify-content: center;

			.radius {
				border-radius: 50%;
				height: 50px;
				width: 50px;
				background-color: #fff;
			}
		}

		.shot {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.item {
			width: 40px;
			height: 40px;
		}
	}
	.countdown-timer {
		font-size: 80px;
		font-weight: bold;
		color: #fff;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
	.isStartDistinguish{
		pointer-events: none !important;
	}
}
</style>
